<template>
  <div>
    <!-- 🍞面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 🪧卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddDialog">添加角色</el-button>
        </el-col>
      </el-row>

      <!--  -->
      <el-table :data="rolesList" border stripe style="width: 100%">
        <el-table-column type="expand">
          <template #default="scope">
            <el-row
              :class="['bd_bottom', i1 === 0 ? 'bd_top' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag type="primary" closeable>{{ item1.authName }}</el-tag>
                <el-icon><CaretRight /></el-icon>
              </el-col>
              <!-- 二三 级权限 -->
              <el-col :span="19">
                <!-- 2 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bd_top', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success" closeable>
                      {{ item2.authName }}</el-tag
                    >
                    <el-icon><CaretRight /></el-icon>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作🤷‍♀️" width="300px">
          <template #default="scope">
            <el-button
              class="cxh"
              type="primary"
              :icon="Edit"
              circle
              size="large"
            />
            <el-button
              class="cxh"
              type="danger"
              :icon="Delete"
              circle
              size="large"
              @click="deleteRoles(scope.row)"
            />
            <el-button
              class="cxh"
              type="warning"
              :icon="Setting"
              circle
              size="large"
              @click="showSetDialog(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--  * 分配权限 -->
    <el-dialog
      v-model="setRightDialogVisible"
      title="分配权限"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- tree -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="allotRights"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- *添加角色 -->
    <el-dialog v-model="showAddRoleDialog" title="添加角色" width="50%">
      <!--  -->
      <el-form
        ref="addRoleRuleFormRef"
        :model="addRoleRuleForm"
        :rules="addRoleRules"
        label-width="120px"
        @close="addRoleClosed"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleRuleForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleRuleForm.roleDesc" />
        </el-form-item>
      </el-form>
      <!--  -->
      <template #footer>
        <span>
          <el-button @click="showAddRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="addRoles"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Delete, Setting, Edit, CaretRight } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, reactive, getCurrentInstance } from 'vue';
const currentInstance = getCurrentInstance();
const { $axios } = currentInstance.appContext.config.globalProperties;

let rolesList = ref();

// 获取角色列表
async function getRolesList() {
  const { data } = await $axios.get('roles');
  console.log(data);
  if (data.meta.status !== 200)
    return ElMessage({
      type: 'error',
      message: '获取角色列表数据失败！',
      showClose: true,
    });

  rolesList.value = data.data;
}
getRolesList();

// *删除权限
const removeRightById = async (role, rightId) => {
  const result = await ElMessageBox.confirm(
    '此操作将永久删除该权限，是否继续?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).catch((err) => err);
  if (result !== 'confirm')
    return ElMessage({
      type: 'info',
      message: '已取消删除',
      showClose: true,
    });

  const { data } = await $axios.delete(`roles/${role.id}/rights/${rightId}`);

  if (data.meta.status !== 200)
    return ElMessage({
      type: 'error',
      message: '删除权限失败！',
      showClose: true,
    });

  ElMessage({
    type: 'success',
    message: '删除权限成功',
    showClose: true,
  });
  role.children.value = data.data;
  getRolesList();
};

// *分配权限 对话框
let setRightDialogVisible = ref(null);
// * 所有权限数据
let rightsList = ref();

let treeProps = reactive({
  children: 'children',
  label: 'authName',
});

// 设置 权限
const showSetDialog = async (role) => {
  const { data } = await $axios.get('rights/tree');
  if (data.meta.status !== 200)
    return ElMessage({
      type: 'error',
      message: '获取用户权限失败！',
      showClose: true,
    });

  rightsList.value = data.data;

  getLeafKeys(role, defKeys.value);

  setRightDialogVisible.value = true;
};

// 默认已勾选
let defKeys = ref([]);
// 递归 获取 角色 所有三级权限
const getLeafKeys = (node, arr) => {
  if (!node.children) {
    return arr.push(node.id);
  }

  node.children.forEach((item) => {
    getLeafKeys(item, arr);
  });
};

const setRightDialogClosed = () => {
  defKeys.value = [];
  setRightDialogVisible.value = false;
};

let treeRef = ref(null);
// 点击 分配权限
const allotRights = async () => {
  const keys = ref([]);
  console.log(treeRef._value);
  const { data } = await $axios.post(`roles/${1}}/rights`);
  console.log(data);
};

// 添加角色 对话框
let showAddRoleDialog = ref(false);

const showAddDialog = () => {
  showAddRoleDialog.value = true;
};
// 添加角色 对话框 关闭
const addRoleClosed = () => {
  addRoleRuleFormRef._value.resetFields();
};
const addRoleRules = reactive({
  roleName: {
    required: true,
    message: 'Please Enter',
    trigger: 'blur',
  },
  roleDesc: {
    required: true,
    message: 'Please Enter',
    trigger: 'blur',
  },
});

let addRoleRuleFormRef = ref(null);
//  params
let addRoleRuleForm = reactive({
  roleId: '',
  roleName: '',
  roleDesc: '',
});
// 点击确认
const addRoles = async () => {
  const { data } = await $axios.post('roles', addRoleRuleForm);
  // console.log(data);
  if (data.meta.status !== 201)
    return ElMessage({
      type: 'danger',
      message: '失败',
    });
  addRoleRuleForm = data.data;
  // console.log(addRoleRuleForm);
  //
  showAddRoleDialog.value = false;
  getRolesList();
};
//  添加角色

// 删除角色
const deleteRoles = (role) => {
  ElMessageBox.confirm('确认删除该角色?', 'Warning', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning',
  })
    .then(async (v) => {
      if (v !== 'confirm')
        return ElMessage({
          type: 'info',
          message: '已取消删除',
          showClose: true,
        });
      const { data } = await $axios.delete(`roles/${role.id}`);
      if (data.meta.status !== 200)
        return ElMessage({
          type: 'danger',
          message: '失败',
        });
      ElMessage({
        type: 'success',
        message: '删除成功',
        showClose: true,
      });
      getRolesList();
    })
    .catch((err) => err);
};
</script>

<style scoped>
.el-tag {
  margin: 10px 20px;
  padding: 10px;
}

.bd_top {
  border-top: 1px solid #eee;
}

.bd_bottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
